<template>
  <!-- Main Content -->
  <section class="container mx-auto mt-6">
    <div class="md:grid md:grid-cols-3 md:gap-4">
      <div class="col-span-1">
        <Upload @addSong="addSong"></Upload>
      </div>
      <div class="col-span-2">
        <div class="bg-white rounded border border-gray-200 relative flex flex-col">
          <div class="px-6 pt-6 pb-5 font-bold border-b border-gray-200">
            <span class="card-title">My Songs</span>
            <i class="fa fa-compact-disc float-right text-green-400 text-2xl"></i>
          </div>
          <div class="p-6">
            <!-- Composition Items -->
            <CompositionItem
              v-for="(song, i) in songs"
              :key="song.docID"
              :song="song"
              @updateSong="updateSong"
              :index="i"
              @removeSong="removeSong"
              @updateUnsavedFlag="updateUnsavedFlag"
            />
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import Upload from '@/components/Upload.vue'
import CompositionItem from '@/components/CompositionItem.vue'
import { onMounted, reactive, ref } from 'vue'
import { songsCollection, auth } from '@/includes/firebase'
import { onBeforeRouteLeave } from 'vue-router'
const songs = reactive([])
const unsavedFlag = ref(false)

const addSong = (document) => {
  const song = {
    ...document.data(),
    docID: document.id
  }
  songs.push(song)
}
const updateSong = ({ index, values }) => {
  songs[index].modified_name = values.modified_name
  songs[index].genre = values.genre
}
const removeSong = (index) => {
  songs.splice(index, 1)
}
const updateUnsavedFlag = (boolean) => {
  unsavedFlag.value = boolean
}
onBeforeRouteLeave((to, from, next) => {
  if (!unsavedFlag.value) {
    next()
  } else {
    // eslint-disable-next-line no-alert, no-restricted-globals
    const leave = confirm('You have unsaved changes. Are you sure you want to leave?')
    next(leave)
  }
})
onMounted(async () => {
  // 从数据库中拿
  const snapshot = await songsCollection.where('uid', '==', auth.currentUser.uid).get()
  snapshot.forEach(addSong)
})
</script>
